package com.swjd.controller;

import com.swjd.pojo.MyFile;
import com.swjd.util.GlobalUtil;
import com.swjd.util.ResultUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping(value = "file/", method = RequestMethod.POST)
public class FileController {

    @RequestMapping(value = "/uploadImg", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public ResultUtil uploadImg(HttpServletRequest req) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;// 转换request，解析出request中的文件
        MultipartFile file = multipartRequest.getFile("icon");
        if (file == null) {
            return ResultUtil.error("文件不能为空！");
        }
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."))
                .toLowerCase();
        if (".jpg".equals(fileType) || ".jpeg".equals(fileType) || ".png".equals(fileType) || ".gif".equals(fileType)) {
            Map<String, String> map = new HashMap<String, String>();
            File save = new File(GlobalUtil.getValue("upFile.iconPath"));
            return SaveFile(map, save, file, fileType);
        } else {
            return ResultUtil.error("文件格式不支持,请重新选择！");
        }
    }

    @RequestMapping(value = "/uploadImgs", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public ResultUtil uploadImgs(HttpServletRequest req) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;// 转换request，解析出request中的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();// 获取文件map集合
        Map<String, String> map = new HashMap<String, String>();
        File save = new File(GlobalUtil.getValue("upFile.iconPath"));
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取单个文件
            if (file == null) {
                return ResultUtil.error("文件不能为空！");
            }
            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."))
                    .toLowerCase();
            if (".jpg".equals(fileType) || ".jpeg".equals(fileType) || ".png".equals(fileType) || ".gif".equals(fileType)) {
                SaveFile(map, save, file, fileType);
            } else {
                return ResultUtil.error("文件格式不支持,请重新选择！");
            }
        }
        return ResultUtil.ok(map);
    }

    private ResultUtil SaveFile(Map<String, String> map, File save, MultipartFile file, String fileType) {
        Random d = new Random();
        String img = UUID.randomUUID().toString().replace("-", "") + d.nextInt(10000) + "" + fileType;
        try {
            if (!save.exists()) {
                save.mkdirs();
            }
            file.transferTo(new File(save, img));
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("src" + (map.size() + 1), img);
        return ResultUtil.ok(map);
    }

    @RequestMapping(value = "/uploadZip", produces = "application/json;charset=utf-8")
    @ResponseBody
    public ResultUtil uploadZip(MultipartFile file, HttpServletRequest req) {
        if (file == null) {
            return ResultUtil.error("文件不能为空！");
        }
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."))
                .toLowerCase();
        if (".zip".equals(fileType) || ".rar".equals(fileType)) {
            Map<String, String> map = new HashMap<String, String>();
            File save = new File(GlobalUtil.getValue("upFile.zipPath"));
            return SaveFile(map, save, file, fileType);
        } else {
            return ResultUtil.error("文件格式不支持,请重新选择！");
        }
    }

    /**
     * 本地图片回显
     *
     * @param response
     * @return
     */
    @RequestMapping(value = "/showPic")
    @ResponseBody
    public String showPic(@RequestBody MyFile requestFile, @RequestParam(required = false) HttpServletResponse response) {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            //图片的本地全路径
            fis = new FileInputStream(GlobalUtil.getValue(requestFile.getFileAddress()) + "/" + requestFile.getFileName());
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    /**
     * 处理文件下载
     *
     * @param response
     */
    @RequestMapping(value = "/downLoad")
    @ResponseBody
    public void downLoadList(@RequestBody MyFile requestFile, @RequestParam(required = false) HttpServletResponse response) {
        downloadFile(new File(GlobalUtil.getValue(requestFile.getFileAddress()), requestFile.getFileName()), response, false);
    }

    /**
     * 文件下载
     *
     * @param file
     * @param response
     * @param isDelete
     */
    public void downloadFile(File file, HttpServletResponse response, boolean isDelete) {
        try {
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            if (isDelete) {
                file.delete();        //是否将生成的服务器端文件删除
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
